<?php
namespace app\controller;

use app\BaseController;

use app\model\User;  // 引入User模型


use think\facade\Db;

use think\facade\View;
use app\model\UserMsg;
use think\Request;


class Auth extends BaseController
{
    public function login()
    { 
        return view('auth/login');
    }
    public function register()
    {
        return view('auth/register');
    }
    public function index()
    {
        return view('auth/index');
    }
    public function welcome()
    {
        return view('auth/welcome');
    }
    public function error()
    {
        return view('auth/404error');
    }



    // 执行登录
    public function  doLogin(Request $request){
        $input = $request->all();
        $res = UserMsg::where(['username'=>$input['username']])->find();
        if($res){
            // 验证密码是否正确
            if (password_verify($input['password'],$res['password'])){
                session('user',$res);
                $data = ['msg'=>'登录成功!','code'=>200];
            }else{
                $data = ['msg'=>'登录失败!密码错误','code'=>403];
            }
        }else{
            $data = ['msg'=>'登录失败!帐号不存在','code'=>403];
        }
        return json($data);
    }
    // 执行注册
    public function  doRegister(Request $request){
        $input = $request->all();
        // 添加注册时间,标志位
        date_default_timezone_set('PRC');
        $input['registerTime'] = date('Y-m-d h:i:s', time());
        $input['isDelete'] = '0';
        // 密码加密
        $input['password']=password_hash($input['password'],PASSWORD_DEFAULT);

        $res = UserMsg::where(['username'=>$input['username']])->find();
        if(!$res){
            // 不能有相同帐号名
            $res1 = UserMsg::create($input);
            $data = ['msg'=>'注册成功!','code'=>200];
        }else{
            $data = ['msg'=>'注册失败!帐号已存在','code'=>403];
        }
        return json($data);
    }

}
